package os.kai.aiu;

import nl.siegmann.epublib.domain.Book;
import nl.siegmann.epublib.domain.Resource;
import nl.siegmann.epublib.epub.EpubReader;

import java.io.*;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Collection;
import java.util.List;

public class ConvertEpubNovelV2 {
    private static final int BUFFER_SIZE = 4096;
    private static void convert(String input, String outputDir) throws IOException {
        byte[] buffer = new byte[BUFFER_SIZE];
        EpubReader reader = new EpubReader();
        try(InputStream ins = Files.newInputStream(Paths.get(input))){
            Book book = reader.readEpub(ins);
            Collection<Resource> resources = book.getResources().getAll();
            for(Resource resource : resources){
                String path = outputDir+File.separator+resource.getHref();
                File file = new File(path);
                File pf = file.getParentFile();
                if(!pf.exists()){
                    if(!pf.mkdirs()){
                        throw new IOException("create dir failed: "+path);
                    }
                }
                try(InputStream rins = resource.getInputStream()){
                    try(OutputStream routs = Files.newOutputStream(file.toPath())){
                        int len;
                        while((len=rins.read(buffer))>0){
                            routs.write(buffer,0,len);
                        }
                    }
                }
            }
        }
    }

    public static void convertWuZhi() throws IOException {
        String input = "D:\\work\\aigc\\novels\\无职转生\\無職轉生(web版譯名統一版)(全卷完).epub";
        String output = "D:\\work\\aigc\\novels\\无职转生\\site";
        convert(input,output);
    }

    public static void convertLuRen() throws IOException {
        String input = "D:\\work\\aigc\\novels\\乙女路人\\乙女游戏世界对路人角色太严厉 1-SS17.epub";
        String output = "D:\\work\\aigc\\novels\\乙女路人\\site";
        convert(input,output);
    }

    public static void main(String[] args) throws IOException {
        convertLuRen();
    }
}
